package com.xw.childhealth.controller;

import com.xw.childhealth.VO.ResultVO;
import com.xw.childhealth.entity.BasicData;
import com.xw.childhealth.enums.ResultEnum;
import com.xw.childhealth.service.BasicDataService;
import com.xw.childhealth.util.ImageUtil;
import com.xw.childhealth.util.PathUtil;
import com.xw.childhealth.util.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: y
 * @CreateDate: 2019-11-27 08:41
 * @Version: 1.0
 */
@RestController
@RequestMapping("/basicData")
@Slf4j
public class BasicDataController {

    @Autowired
    private BasicDataService basicDataService;


    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    @RequestMapping("/findBasicData")
    public ResultVO findBasicData(@RequestParam(value = "size", defaultValue = "10") Integer size, @RequestParam(value = "page", defaultValue = "0") Integer page, HttpServletRequest request) {

        Specification<BasicData> specification = new Specification<BasicData>() {
            @Override
            public Predicate toPredicate(Root<BasicData> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                //集合 用于封装查询条件
                List<Predicate> list = new ArrayList<Predicate>();
                String searchName = request.getParameter("searchName");
                if (!StringUtils.isEmpty(searchName)) {
                    Predicate p1 = criteriaBuilder.like(root.get("xm").as(String.class), "%" + searchName.trim() + "%");
                    list.add(p1);
                }
                String searchDah = request.getParameter("searchDah");
                if (!StringUtils.isEmpty(searchDah)) {
                    Predicate p2 = criteriaBuilder.like(root.get("dah").as(String.class), "%" + searchDah.trim() + "%");
                    list.add(p2);
                }

                String start = request.getParameter("start");
                String end = request.getParameter("end");
                if (!StringUtils.isEmpty(start) && !StringUtils.isEmpty(end)) {
                    Predicate p3 = criteriaBuilder.between(root.get("createTime").as(String.class), start, end);
                    list.add(p3);
                } else if (!StringUtils.isEmpty(start)) {
                    Predicate p4 = criteriaBuilder.between(root.get("createTime").as(String.class), start, "2222-02-02");
                    list.add(p4);
                }


                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            }
        };

        Sort sort = Sort.by(Sort.Order.desc("createTime"));//创建时间倒叙查询2  1
        PageRequest pageRequest = PageRequest.of(page < 0 ? 0 : page, size, sort);
        Page<BasicData> all = basicDataService.findAll(specification, pageRequest);
        return ResultVOUtil.success(all);
    }


    @Transactional
    @RequestMapping("/data-upd")
    public ModelAndView edit(BasicData basicData, MultipartFile file, HttpServletRequest request, @RequestParam(value = "id", required = false) Integer id, @RequestParam(value = "type", required = false) String type,
                             Map<String, Object> map) {
        if (type == null)
            return new ModelAndView("/pages/admin/basic-data", map);

        if (type.equals("toUpd")) {
            BasicData one = basicDataService.findById(id);
            map.put("type", type);
            map.put("result", one);
        } else if (type.equals("upd")) {
            BasicData bd = basicDataService.findById(id);
            if (file.getOriginalFilename() != "" && !file.getOriginalFilename().isEmpty() && file.getOriginalFilename() != null) {
                String dest = PathUtil.getImgPath(sdf.format(new Date()));
                String imgAddr = ImageUtil.generateThumbnail(file, dest);
                basicData.setTx(imgAddr);
            } else {
                basicData.setTx(bd.getTx());
            }
            basicData.setUpdateTime(new Date());
            basicData.setCreateTime(bd.getCreateTime());
            BeanUtils.copyProperties(basicData, bd);
            basicDataService.save(bd);
            return new ModelAndView("/pages/admin/basic-data", map);
        }
        if (type.equals("add")) {
            String dest = PathUtil.getImgPath(sdf.format(new Date()));
            String imgAddr = ImageUtil.generateThumbnail(file, dest);
            BasicData save = basicDataService.save(basicData.setCreateTime(new Date()).setUpdateTime(new Date()).setTx(imgAddr));
            return new ModelAndView("/pages/admin/basic-data", map);
        } else if (type.equals("toAdd")) {
            map.put("result", new BasicData().setId(0));
        }
        return new ModelAndView("/pages/admin/basic-data-add", map);
    }

    @RequestMapping(value = "/userImage", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] userImage(@RequestParam("str") String str) throws Exception {

        String dest = PathUtil.getImgBasePath() + str;

        if (!dest.contains(".")) {
            return null;
        }
        FileInputStream inputStream = new FileInputStream(new File(dest));
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;

    }

    @PostMapping("/data-del")
    public ResultVO dataDel(@RequestParam("id") Integer id) {
        BasicData result = basicDataService.findById(id);
        if (result != null) {
            basicDataService.delById(id);
            return ResultVOUtil.success();
        }
        return ResultVOUtil.error(ResultEnum.DEL_ERR);
    }

}
